package com.example.demo.controller;

import com.example.demo.entity.ShopCart;
import com.example.demo.mapper.ShopCartMapper;
import com.example.demo.utils.PagingResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/shop-cart") // 控制器的前缀地址
public class ShopCartController {
    @Autowired
    ShopCartMapper shopCartMapper;

    /**
     * 获取分页的购物车数据
     * @param limit 每页数量
     * @param offset 偏移量
     * @param field 搜索字段
     * @param code 搜索关键词
     * @return 分页结果
     */
    @GetMapping("/list")
    public PagingResult<ShopCart> select(
            @RequestParam(required = false, name = "limit", defaultValue = "10") int limit,
            @RequestParam(required = false, name = "offset", defaultValue = "0") int offset,
            @RequestParam(required = false, name = "field") String field,
            @RequestParam(required = false, name = "code") String code
    ) {
        List<ShopCart> shopCartList;
        int total;
        
        if (field != null && code != null && !code.isEmpty()) {
            // 带搜索条件的查询
            shopCartList = shopCartMapper.findBySearch(offset, limit, field, code);
            total = shopCartMapper.countBySearch(field, code);
        } else {
            // 不带搜索条件的查询
            shopCartList = shopCartMapper.findByPage(offset, limit);
            total = shopCartMapper.count();
        }
        
        return new PagingResult<ShopCart>(shopCartList, total);
    }

    /**
     * 根据ID获取购物车
     * @param id 购物车ID
     * @return 购物车对象
     */
    @GetMapping("/{id}")
    public ShopCart getById(@PathVariable("id") int id) {
        return shopCartMapper.findById(id);
    }

    /**
     * 添加购物车
     * @param shopCart 购物车对象
     * @return 影响行数
     */
    @PostMapping("/add")
    public int add(@RequestBody ShopCart shopCart) {
        return shopCartMapper.insert(shopCart);
    }

    /**
     * 更新购物车
     * @param shopCart 购物车对象
     * @return 影响行数
     */
    @PutMapping("/update")
    public int update(@RequestBody ShopCart shopCart) {
        return shopCartMapper.update(shopCart);
    }

    /**
     * 删除购物车
     * @param id 购物车ID
     * @return 影响行数
     */
    @DeleteMapping("/delete/{id}")
    public int delete(@PathVariable("id") int id) {
        return shopCartMapper.delete(id);
    }
}